package com.fms.fmsapi.common.handler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SimpleQuery;
import com.fms.fmsapi.entity.Check;
import com.fms.fmsapi.entity.User;
import com.fms.fmsapi.mapper.CheckMapper;
import com.fms.fmsapi.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 定时任务类
 */
@Component
@Slf4j
public class ScheduledTask {

    @Autowired
    CheckMapper checkMapper;

    @Autowired
    UserMapper userMapper;

    /**
     * 定时发布打卡任务
     *
     */
    @Async//开启异步任务
    //第一个参数是设置任务的调用频率单位是毫秒，第二个参数是启动项目之后间隔多久开始定时任务
    @Scheduled(fixedRateString = "10000", initialDelay = 0)
    public void executeSaveClimateData(){
        Check check = new Check();
        List<User> users = userMapper.selectList(null);
        LocalDate currentDate = LocalDate.now(); // 获取当前日期

        for (User user : users) {
            QueryWrapper<Check> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_uuid", user.getUuid())
                    .eq("DATE_FORMAT(start_time, '%Y-%m-%d')", currentDate.toString());

            Long count = checkMapper.selectCount(queryWrapper); // 查询当前日期的打卡任务数量

            if (count == 0) {
                check.setUuid(String.valueOf(UUID.randomUUID()));//手动生成uuid
                check.setUserUuid(user.getUuid());
                check.setStatus(0);
                check.setStartTime(LocalDateTime.of(currentDate, LocalTime.MIDNIGHT)); // 设置当前日期的开始时间
                check.setImg("");
                checkMapper.insert(check); // 插入新的打卡任务
                log.info(
                        "用户" + user.getUsername() + "的" + currentDate + "打卡任务发布完成"
                );
            }
        }


    }



}
